package com.triones.ljr.controller.web;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.triones.ljr.entity.dto.OvertDeptDO;
import com.triones.ljr.entity.dto.OvertEnterpriseDO;
import com.triones.ljr.entity.vo.OvertDeptVO;
import com.triones.ljr.entity.vo.OvertEnterpriseImportVo;
import com.triones.ljr.entity.vo.OvertEnterpriseVO;
import com.triones.ljr.mapper.OvertDeptMapper;
import com.triones.ljr.service.OvertService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 企业公开
 *
 * @Author: triones
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/overt")
public class OvertController extends BaseController {

    private final OvertService overtService;

    private final OvertDeptMapper overtDeptMapper;

    /**
     * 部门-查询列表（分页）
     */
    @SaCheckPermission("system:overtDept:pageList")
    @GetMapping("/dept/pageList")
    public TableDataInfo<OvertDeptVO> deptPageList(OvertDeptDO dto, PageQuery pageQuery) {
        return overtService.deptPageList(dto,pageQuery);
    }

    /**
     * 部门-查询详细
     * @param id
     */
    @GetMapping(value = "/dept/{id}")
    public R<OvertDeptVO> getDeptInfo(@PathVariable Long id) {
        return R.ok(overtService.getDeptInfo(id));
    }

    /**
     * 部门-新增
     */
    @SaCheckPermission("system:overtDept:add")
    @Log(title = "公开企业", businessType = BusinessType.INSERT)
    @PostMapping("/dept")
    public R<Void> addDept(@Validated @RequestBody OvertDeptDO dto) {
        if (!overtService.checkDeptNameUnique(dto)) {
            return R.fail("新增部门'" + dto.getDeptName() + "'失败，部门已存在");
        }
        return toAjax(overtService.addDept(dto));
    }

    /**
     * 部门-修改
     */
    @SaCheckPermission("system:overtDept:edit")
    @Log(title = "公开企业", businessType = BusinessType.INSERT)
    @PutMapping("/dept")
    public R<Void> editDept(@Validated @RequestBody OvertDeptDO dto) {
        if (!overtService.checkDeptNameUnique(dto)) {
            return R.fail("修改部门'" + dto.getDeptName() + "'失败，部门已存在");
        }
        return toAjax(overtService.editDept(dto));
    }

    /**
     * 部门-删除
     * @param id
     */
    @SaCheckPermission("system:overtDept:remove")
    @Log(title = "公开企业", businessType = BusinessType.INSERT)
    @DeleteMapping("/dept/{id}")
    public R<Void> removeDept(@PathVariable Long id) {
        return toAjax(overtService.removeDept(id));
    }


    /**
     * 部门-获取列表
     */
    @GetMapping("/dept/optionSelect")
    public R<List<OvertDeptVO>> optionSelect() {
        return R.ok(overtService.selectDeptAll(null));
    }

    /**
     * 企业-查询列表（分页）
     */
    @SaCheckPermission("system:overtEnterprise:pageList")
    @GetMapping("/enterprise/pageList")
    public TableDataInfo<OvertEnterpriseVO> enterprisePageList(OvertEnterpriseDO dto, PageQuery pageQuery) {
        return overtService.enterprisePageList(dto, pageQuery);
    }

    /**
     * 企业-查询详细
     * @param id
     */
    @GetMapping(value = "/enterprise/{id}")
    public R<OvertEnterpriseVO> getEnterpriseInfo(@PathVariable Long id) {
        return R.ok(overtService.getEnterpriseInfo(id));
    }

    /**
     * 企业-新增
     */
    @SaCheckPermission("system:overtEnterprise:add")
    @Log(title = "企业公开", businessType = BusinessType.INSERT)
    @PostMapping("/enterprise")
    public R<Void> addEnterprise(@Validated @RequestBody OvertEnterpriseDO dto) {
        if (!overtService.checkEnterpriseNameUnique(dto)) {
            return R.fail("新增企业'" + dto.getName() + "'失败，企业名称已存在");
        }
        return toAjax(overtService.addEnterprise(dto));
    }

    /**
     * 企业-修改
     */
    @SaCheckPermission("system:overtEnterprise:edit")
    @Log(title = "企业公开", businessType = BusinessType.INSERT)
    @PutMapping("/enterprise")
    public R<Void> editEnterprise(@Validated @RequestBody OvertEnterpriseDO dto) {
        if (!overtService.checkEnterpriseNameUnique(dto)) {
            return R.fail("修改企业'" + dto.getName() + "'失败，企业名称已存在");
        }
        return toAjax(overtService.editEnterprise(dto));
    }

    /**
     * 企业-删除
     * @param id
     */
    @SaCheckPermission("system:overtEnterprise:remove")
    @Log(title = "企业公开", businessType = BusinessType.INSERT)
    @DeleteMapping("/enterprise/{id}")
    public R<Void> removeEnterprise(@PathVariable Long id) {
        return toAjax(overtService.removeEnterprise(id));
    }

    /**
     * 导入数据
     *
     * @param file 导入文件
     */
    @Log(title = "公开企业", businessType = BusinessType.IMPORT)
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData(@RequestPart("file") MultipartFile file) throws Exception {
        ExcelResult<OvertEnterpriseImportVo> excelResult = ExcelUtil.importExcel(file.getInputStream(), OvertEnterpriseImportVo.class, true);
        List<OvertEnterpriseImportVo> voList = excelResult.getList();
        List<OvertEnterpriseDO> list = new ArrayList<>();
        if (voList != null && voList.size() > 0) {
            for (OvertEnterpriseImportVo importVo : voList) {
                OvertDeptDO overtDeptDO = overtDeptMapper.selectOne(new LambdaQueryWrapper<OvertDeptDO>()
                    .eq(OvertDeptDO::getDeptName, importVo.getDeptName())
                    .eq(OvertDeptDO::getIsDel, "0").last("limit 1"));
                if (overtDeptDO != null) {
                    OvertEnterpriseDO enterpriseDO = new OvertEnterpriseDO();
                    enterpriseDO.setCreateTime(DateUtil.getDateTimeString());
                    enterpriseDO.setName(importVo.getName());
                    enterpriseDO.setCategory(importVo.getCategory());
                    enterpriseDO.setDid(overtDeptDO.getId());
                    enterpriseDO.setLiaison(importVo.getLiaison());
                    enterpriseDO.setLiaisonTel(importVo.getLiaisonTel());
                    enterpriseDO.setSort(0);
                    list.add(enterpriseDO);
                } else {
                    overtDeptDO = new OvertDeptDO();
                    overtDeptDO.setDeptName(importVo.getDeptName());
                    overtDeptDO.setSort(0);
                    overtDeptDO.setCreateTime(DateUtil.getDateTimeString());
                    overtDeptMapper.insert(overtDeptDO);
                    OvertEnterpriseDO enterpriseDO = new OvertEnterpriseDO();
                    enterpriseDO.setCreateTime(DateUtil.getDateTimeString());
                    enterpriseDO.setName(importVo.getName());
                    enterpriseDO.setCategory(importVo.getCategory());
                    enterpriseDO.setDid(overtDeptDO.getId());
                    enterpriseDO.setLiaison(importVo.getLiaison());
                    enterpriseDO.setLiaisonTel(importVo.getLiaisonTel());
                    enterpriseDO.setSort(0);
                    list.add(enterpriseDO);
                }
            }
        }
        overtService.saveBatch(list);
        return R.ok(excelResult.getAnalysis());
    }
}
